package com.usian.controller;

import com.usian.CartFeign;
import com.usian.feign.ItemServiceFeign;
import com.usian.pojo.TbItem;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RequestMapping("/frontend/cart")
@RestController
public class CartController {
    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private ItemServiceFeign itemServiceFeign;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Value("${CART_COOKIE_EXPIRE}")
    private Integer CART_COOKIE_EXPIRE;


    /**
     * 未登录状态先，将信息添加都购物车 cookie
     * @param request
     * @param response
     * @param itemId
     * @param userId
     * @param num
     * @return
     */
    @RequestMapping("addItem")
    public Result addItem(HttpServletRequest request, HttpServletResponse response, @RequestParam  Long itemId,@RequestParam String userId, @RequestParam(defaultValue = "1") Integer num){
        try{
            //判断userId是否存在
            if (StringUtils.isBlank(userId)){
                /* 用户未登录情况下 */
                //1.从cookie中查询商品列表
                Map<String,TbItem> map=getCartFromCookie(request);
                //2.添加到购物车
                addItemToCart(map,itemId,num);
                //将购物车加入到cookie
                addClientCookie(request,response,map);
            }else{
                //登陆状态
                // 1、从redis中查询商品列表。
                Map<String,TbItem> cart = getCartFromRedis(userId);
                //Map<String,TbItem> map1=getCartFromCookie(request);

                //2、将商品添加大购物车中
                this.addItemToCart(cart,itemId,num);
                //3、将购物车缓存到 redis 中
                Boolean addCartToRedis = this.addCartToRedis(userId, cart);
                if(addCartToRedis){
                    return Result.ok();
                }
                return Result.error("error");

            }
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("error");
        }
    }

    /**
     * 把购车商品列表写入redis
     * @param userId
     * @param cart
     */
    private Boolean addCartToRedis(String userId, Map<String, TbItem> cart) {
        return cartFeign.insertCart(userId, cart);
    }

    /**
     * 从redis中查询购物车
     * @param userId
     */
    private Map<String,TbItem> getCartFromRedis(String userId) {
        Map<String,TbItem> cart = cartFeign.selectCartByUserId(userId);
        if(cart!=null && cart.size()>0){
            return cart;
        }
        return new HashMap<String,TbItem>();
    }

    /**
     * 把购车商品列表写入cookie
     * @param request
     * @param response
     * @param map
     */
    private void addClientCookie(HttpServletRequest request, HttpServletResponse response, Map<String, TbItem> map) {
        String s = JsonUtils.objectToJson(map);
        CookieUtils.setCookie(request, response, this.CART_COOKIE_KEY , s , CART_COOKIE_EXPIRE , true);
    }

    /**
     * 将商品添加到购物车中
     * @param map
     * @param itemId
     * @param num
     */
    private void addItemToCart(Map<String, TbItem> map, Long itemId, Integer num) {
        //先从购物车中取商品
        TbItem tbItem = map.get(itemId.toString());
        //判断是否存在
        if (tbItem != null){
            //若存在 数量商品相加
            tbItem.setNum(tbItem.getNum()+num);
        }else{
             //若不存在  根据id查询商品 并将其添加到购物车
             tbItem = itemServiceFeign.selectItemInfo(itemId);
             tbItem.setNum(num);
        }
        map.put(itemId.toString(),tbItem);
    }


    /**
     * 获取购物车
     * @param request
     * @return
     */
    private Map<String, TbItem> getCartFromCookie(HttpServletRequest request) {
        String cookieValue = CookieUtils.getCookieValue(request, this.CART_COOKIE_KEY, true);
        if (StringUtils.isNotBlank(cookieValue)){
            //购物车已存在
            Map map = JsonUtils.jsonToMap(cookieValue, TbItem.class);
            return map;
        }
        //购物车不存在
        return new HashMap<String, TbItem>();
    }


    /**
     * 查看购物车
     * @param userId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/showCart")
    public Result showCart(String userId,HttpServletRequest
            request,HttpServletResponse response){
        try{
            List<TbItem> list = new ArrayList<TbItem>();
            if(StringUtils.isBlank(userId)){
                //在用户未登录的状态下
                Map<String,TbItem> cart = this.getCartFromCookie(request);
                Set<String> keys = cart.keySet();
                for(String key :keys){
                    list.add(cart.get(key));
                }
            }else{
                // 在用户已登录的状态Tb
                List<TbItem> list1=new ArrayList<>();
                Map<String, TbItem> cartFromRedis = getCartFromRedis(userId);
                Set<String> strings = cartFromRedis.keySet();
                for (String string : strings) {
                    list.add(cartFromRedis.get(string));
                }
            }
            return Result.ok(list);
        }catch(Exception e){
            e.printStackTrace();
        }
        return Result.error("error");
    }


    /**
     * 修改购物车
     */
    @RequestMapping("/updateItemNum")
    public Result updateItemNum(String userId,Long itemId,Integer num,
                                HttpServletRequest request,HttpServletResponse response){
        try {
            if(StringUtils.isBlank(userId)){
                //未登录
                //1、获得cookie中的购物车
                Map<String, TbItem> cart = getCartFromCookie(request);
                //2、修改购物车中的商品
                TbItem tbItem = cart.get(itemId.toString());
                tbItem.setNum(num);
                cart.put(itemId.toString(),tbItem);
                //3、把购物车写到cookie
                addClientCookie(request, response, cart);
            }else{
                //登录状态下
                //获取redis的购物车
                Map<String, TbItem> cartFromRedis = getCartFromRedis(userId);
                //修改购物车的商品
                TbItem tbItem = cartFromRedis.get(itemId.toString());
                tbItem.setNum(num);
                cartFromRedis.put(itemId.toString(),tbItem);
                //将购物车添加到redis中
                addCartToRedis(userId,cartFromRedis);
            }
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("修改失败");
        }
    }

    /**
     * 删除购物车
     * @param itemId
     * @param userId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("deleteItemFromCart")
    public Result deleteItemFromCart(Long itemId,String userId, HttpServletRequest request,HttpServletResponse response){
        try {
            if (StringUtils.isBlank(userId)){
                //未登录情况下
                //获取redis中的购物车
                Map<String, TbItem> cartFromCookie = getCartFromCookie(request);
                //删除商品信息
                cartFromCookie.remove(itemId.toString());
                //将购物车写进redis
                this.addClientCookie(request,response,cartFromCookie);
            }else{
                //登陆状态下
                //获取redis中的购物车
                Map<String, TbItem> cartFromRedis = getCartFromRedis(userId);
                //删除商品信息
                cartFromRedis.remove(itemId.toString());
                //将购物车写进redis
                addCartToRedis(userId,cartFromRedis);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("删除失败");
    }

}
